import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/flutter_svg.dart';

import '../../common/index.dart';

import 'widgets/calendar_bottom_sheet.dart';
import 'widgets/publish_bottom_sheet.dart';

class HomePage extends ConsumerStatefulWidget {
  const HomePage({super.key});

  @override
  ConsumerState<HomePage> createState() => _HomePageState();
}

class _HomePageState extends ConsumerState<HomePage> {
  DateTime _selectedDate = DateTime.now();
  int _selectedDateIndex = 0;

  @override
  void initState() {
    super.initState();
    // 初始化选中今天的日期索引
    _initializeSelectedDateIndex();
    // 延迟加载当前用户的分享数据，避免在widget构建期间修改provider
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadUserShares();
    });
  }

  void _loadUserShares() {
    final currentUser = ref.read(currentUserProvider);
    if (currentUser != null) {
      ref.read(shareProvider.notifier).loadSharesByUserId(currentUser.id);
    }
  }

  void _initializeSelectedDateIndex() {
    final dates = _generateWeekDates();
    final today = DateTime.now();
    for (int i = 0; i < dates.length; i++) {
      if (_isSameDay(dates[i]['date'], today)) {
        _selectedDateIndex = i;
        _selectedDate = today;
        break;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final currentUser = ref.watch(currentUserProvider);

    return Scaffold(
      resizeToAvoidBottomInset: true,
      body: Container(
        height: MediaQuery.of(context).size.height,
        width: MediaQuery.of(context).size.width,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MyImages.homeBg),
            fit: BoxFit.fill,
          ),
        ),
        child: SafeArea(
          top: false,
          bottom: false,
          child: Column(
            children: [
              SizedBox(height: 55.h),
              _buildTopSection(currentUser?.username ?? 'Guest'),

              // 其他内容
              Expanded(child: _buildSharesList()),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildTopSection(String username) {
    return SizedBox(
      height: 185.h,
      width: double.infinity,
      child: Column(
        children: [
          // 上半部分 - 用户名和按钮行
          _buildTopRow(username),
          SizedBox(height: 20.h),
          // 下半部分 - 日期滑动列表
          _buildDateScrollList(),
        ],
      ),
    );
  }

  Widget _buildTopRow(String username) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: Row(
        children: [
          // 用户名
          Text(
            '👋Hey, $username!',
            style: TextStyle(
              color: Colors.white,
              fontSize: 24.sp,
              fontFamily: 'Port',
              fontWeight: FontWeight.w400,
            ),
          ),
          Spacer(),
          // 日历按钮
          _buildCalendarButton(),
          SizedBox(width: 5.w),
          // 发布按钮
          GestureDetector(
            onTap: _showPublishBottomSheet,
            child: SvgPicture.asset(MyIcons.set, width: 24.w, height: 24.h),
          ),
          SizedBox(width: 10.w),
        ],
      ),
    );
  }

  Widget _buildCalendarButton() {
    return GestureDetector(
      onTap: _showCalendarBottomSheet,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 10.h),
        decoration: ShapeDecoration(
          color: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20.r),
          ),
          shadows: [
            BoxShadow(
              color: Color(0x05000000),
              blurRadius: 8,
              offset: Offset(0, 1),
              spreadRadius: 0,
            ),
          ],
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Row(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              spacing: 8,
              children: [
                Text(
                  _getSelectedDateString(),
                  style: TextStyle(
                    color: const Color(0xFF100F11),
                    fontSize: 14.sp,
                    fontFamily: 'Pangram',
                    fontWeight: FontWeight.w400,
                    height: 1.43,
                  ),
                ),
                SvgPicture.asset(MyIcons.calendar, width: 20.w, height: 20.h),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDateScrollList() {
    // 生成一周的日期数据
    final dates = _generateWeekDates();

    return SizedBox(
      height: 120.h, // 增加高度以容纳emotion图片
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        padding: EdgeInsets.symmetric(horizontal: 20.w),
        itemCount: dates.length,
        itemBuilder: (context, index) {
          final date = dates[index];
          final isSelected = _selectedDateIndex == index;
          return Padding(
            padding: EdgeInsets.only(
              right: index < dates.length - 1 ? 12.w : 0,
            ),
            child: _buildDateItem(date, isSelected, index),
          );
        },
      ),
    );
  }

  Widget _buildDateItem(Map<String, dynamic> date, bool isSelected, int index) {
    final DateTime itemDate = date['date'];
    final DateTime today = DateTime.now();
    final bool isSelectableDate =
        itemDate.isBefore(today) || _isSameDay(itemDate, today);

    // 获取该日期的emotion
    final emotion = _getEmotionForDate(itemDate);

    return GestureDetector(
      onTap: isSelectableDate
          ? () {
              setState(() {
                _selectedDateIndex = index;
                _selectedDate = date['date'];
              });
              // 延迟重新加载用户分享数据
              Future.microtask(() => _loadUserShares());
            }
          : null,
      child: Column(
        children: [
          // 日期container
          Container(
            width: 47.w,
            height: 75.h,
            padding: EdgeInsets.only(
              top: 8.h,
              left: 8.w,
              right: 8.w,
              bottom: 8.h,
            ),
            decoration: ShapeDecoration(
              gradient: isSelected
                  ? const LinearGradient(
                      begin: Alignment(0.00, 0.50),
                      end: Alignment(1.00, 0.50),
                      colors: [Color(0xFFFF8C00), Color(0xFFF8FFC7)],
                    )
                  : null,
              color: isSelected
                  ? null
                  : isSelectableDate
                  ? Colors.white
                  : Colors.white.withValues(alpha: 0.5),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(25.r),
              ),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              spacing: 4,
              children: [
                Text(
                  date['dayName'],
                  style: TextStyle(
                    color: isSelected
                        ? Colors.white
                        : isSelectableDate
                        ? const Color(0xFF100F11)
                        : const Color(0xFF100F11).withValues(alpha: 0.4),
                    fontSize: 14.sp,
                    fontFamily: 'Pangram',
                    fontWeight: FontWeight.w400,
                    height: 1.43,
                  ),
                ),
                Text(
                  date['day'].toString(),
                  style: TextStyle(
                    color: isSelected
                        ? Colors.white
                        : isSelectableDate
                        ? const Color(0xFF100F11)
                        : const Color(0xFF100F11).withValues(alpha: 0.4),
                    fontSize: 18.sp,
                    fontFamily: 'Pangram',
                    fontWeight: FontWeight.w500,
                    height: 1.11,
                  ),
                ),
              ],
            ),
          ),

          SizedBox(height: 5.h),
          if (emotion != null && emotion.isNotEmpty)
            Container(
              width: 34.w,
              height: 34.h,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(17.r),
                gradient: isSelected
                    ? const LinearGradient(
                        begin: Alignment.centerLeft,
                        end: Alignment.centerRight,
                        colors: [Color(0xFFFF8C00), Color(0xFFF8FFC7)],
                      )
                    : null,
                color: isSelected ? null : Colors.white.withValues(alpha: 0.6),
              ),
              child: Center(
                child: Image.asset(
                  getEmotionByName(emotion).image,
                  width: 18.w,
                  height: 18.h,
                  fit: BoxFit.contain,
                ),
              ),
            ),
        ],
      ),
    );
  }

  List<Map<String, dynamic>> _generateWeekDates() {
    final List<Map<String, dynamic>> dates = [];

    // 获取选择日期所在周的开始日期（周一）
    final startOfWeek = _selectedDate.subtract(
      Duration(days: _selectedDate.weekday - 1),
    );

    // 生成一周的日期
    for (int i = 0; i < 7; i++) {
      final date = startOfWeek.add(Duration(days: i));
      final dayNames = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

      dates.add({
        'day': date.day,
        'dayName': dayNames[date.weekday - 1],
        'date': date,
      });
    }

    return dates;
  }

  String _getSelectedDateString() {
    final dayNames = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
    final monthNames = [
      'Jan',
      'Feb',
      'Mar',
      'Apr',
      'May',
      'Jun',
      'Jul',
      'Aug',
      'Sep',
      'Oct',
      'Nov',
      'Dec',
    ];

    final dayName = dayNames[_selectedDate.weekday - 1];
    final monthName = monthNames[_selectedDate.month - 1];

    return '$dayName, ${_selectedDate.day} $monthName';
  }

  void _showCalendarBottomSheet() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => CalendarBottomSheet(
        selectedDate: _selectedDate,
        onDateSelected: (DateTime date) {
          // 检查选择的日期是否是今天或今天之前
          final today = DateTime.now();
          if (date.isAfter(today) && !_isSameDay(date, today)) {
            // 如果选择的是未来日期，不允许选择
            return;
          }

          setState(() {
            _selectedDate = date;
            // 更新选中的日期索引，如果选择的日期在当前周内
            _updateSelectedDateIndex(date);
          });
          // 延迟重新加载用户分享数据
          Future.microtask(() => _loadUserShares());
        },
      ),
    );
  }

  void _showPublishBottomSheet() async {
    final currentUser = ref.read(currentUserProvider);
    if (currentUser == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Please login to publish'),
          backgroundColor: Colors.red,
          duration: const Duration(milliseconds: 750),
        ),
      );
      return;
    }

    // 检查非VIP用户是否今天已经发布过
    if (!currentUser.isVip) {
      final hasSharedToday = await UserService.hasSharedToday();
      if (hasSharedToday && mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
              'Non-VIP users can only publish once per day. Upgrade to VIP for unlimited publishing!',
            ),
            backgroundColor: Colors.orange,
            duration: const Duration(milliseconds: 2000),
          ),
        );
        return;
      }
    }

    if (mounted) {
      showModalBottomSheet(
        context: context,
        isScrollControlled: true,
        backgroundColor: Colors.transparent,
        builder: (context) => const PublishBottomSheet(),
      );
    }
  }

  void _updateSelectedDateIndex(DateTime selectedDate) {
    final dates = _generateWeekDates();
    int newIndex = -1;

    // 首先检查选择的日期是否在当前周内
    for (int i = 0; i < dates.length; i++) {
      if (_isSameDay(dates[i]['date'], selectedDate)) {
        newIndex = i;
        break;
      }
    }

    if (newIndex != -1) {
      // 如果在当前周内，直接设置索引
      _selectedDateIndex = newIndex;
    } else {
      // 如果不在当前周内，需要重新生成包含选择日期的周数据
      _generateWeekDatesForSelectedDate(selectedDate);
    }
  }

  void _generateWeekDatesForSelectedDate(DateTime selectedDate) {
    // 重新生成以选择日期为中心的一周数据
    final startOfWeek = selectedDate.subtract(
      Duration(days: selectedDate.weekday - 1),
    );

    // 找到选择日期在新周中的索引
    for (int i = 0; i < 7; i++) {
      final date = startOfWeek.add(Duration(days: i));
      if (_isSameDay(date, selectedDate)) {
        _selectedDateIndex = i;
        break;
      }
    }
  }

  bool _isSameDay(DateTime date1, DateTime date2) {
    return date1.year == date2.year &&
        date1.month == date2.month &&
        date1.day == date2.day;
  }

  /// 获取指定日期的第一个分享的emotion
  String? _getEmotionForDate(DateTime date) {
    final currentUser = ref.read(currentUserProvider);

    // 如果用户未登录，不显示emotion
    if (currentUser == null) {
      return null;
    }

    final shareState = ref.read(shareProvider);

    // 找到该日期的所有分享
    final dayShares = shareState.shares.where((share) {
      final shareDate = DateTime.parse(share.date);
      return _isSameDay(shareDate, date);
    }).toList();

    if (dayShares.isEmpty) {
      return null;
    }

    // 按时间排序，返回第一个分享的emotion
    dayShares.sort(
      (a, b) => DateTime.parse(a.date).compareTo(DateTime.parse(b.date)),
    );
    return dayShares.first.emotion;
  }

  Widget _buildSharesList() {
    final currentUser = ref.watch(currentUserProvider);
    final shareState = ref.watch(shareProvider);

    if (currentUser == null) {
      return Center(
        child: Text(
          'Please login to view shares',
          style: TextStyle(
            color: Colors.white,
            fontSize: 16.sp,
            fontFamily: 'Pangram',
          ),
        ),
      );
    }

    if (shareState.isLoading) {
      return Center(child: CircularProgressIndicator(color: Colors.white));
    }

    if (shareState.error != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'Error: ${shareState.error}',
              style: TextStyle(
                color: Colors.red,
                fontSize: 14.sp,
                fontFamily: 'Pangram',
              ),
            ),
            SizedBox(height: 16.h),
            ElevatedButton(
              onPressed: () => Future.microtask(() => _loadUserShares()),
              child: Text('Retry'),
            ),
          ],
        ),
      );
    }

    // 根据选中的日期过滤分享
    final filteredShares = shareState.shares.where((share) {
      final shareDate = DateTime.parse(share.date);
      return _isSameDay(shareDate, _selectedDate);
    }).toList();

    if (filteredShares.isEmpty) {
      return RefreshIndicator(
        onRefresh: () async {
          final currentUser = ref.read(currentUserProvider);
          if (currentUser != null) {
            await ref
                .read(shareProvider.notifier)
                .loadSharesByUserId(currentUser.id);
          }
        },
        child: ListView(
          padding: EdgeInsets.symmetric(horizontal: 20.w),
          children: [
            SizedBox(height: 75.h),
            Center(
              child: Column(
                children: [
                  Image.asset(MyImages.noShare, width: 113.w, height: 131.h),
                  SizedBox(height: 16.h),
                  Text(
                    'How are you feeling today?',
                    style: TextStyle(
                      color: const Color(0xFFFF8C00),
                      fontSize: 14,
                      fontFamily: 'inter',
                      fontWeight: FontWeight.w600,
                      height: 1.05,
                    ),
                  ),
                  SizedBox(height: 8.h),
                  GestureDetector(
                    onTap: _showPublishBottomSheet,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Container(
                          width: 35.w,
                          height: 35.h,
                          decoration: BoxDecoration(
                            border: Border.all(
                              color: const Color(0xFFCCCCCC),
                              width: 2.w,
                            ),
                            shape: BoxShape.circle,
                          ),
                          child: Icon(
                            Icons.add,
                            color: const Color(0xFFCCCCCC),
                            size: 21.w,
                          ),
                        ),
                        Text(
                          'Check-In',
                          style: TextStyle(
                            color: const Color(0xFFCCCCCC),
                            fontSize: 14.sp,
                            fontFamily: 'inter',
                            fontWeight: FontWeight.w600,
                            height: 1.05,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: () async {
        final currentUser = ref.read(currentUserProvider);
        if (currentUser != null) {
          await ref
              .read(shareProvider.notifier)
              .loadSharesByUserId(currentUser.id);
        }
      },
      child: ListView.builder(
        padding: EdgeInsets.symmetric(horizontal: 10.w),
        itemCount: filteredShares.length,
        itemBuilder: (context, index) {
          final share = filteredShares[index];
          return GestureDetector(
            onTap: () async {
              // 增加浏览量
              await ref
                  .read(shareProvider.notifier)
                  .incrementViewCount(share.id);

              AppRouterExtension(context).navigateTo(
                AppRoutes.shareDetail,
                params: {'shareId': share.id},
              );
            },
            child: ShareItem(share: share),
          );
        },
      ),
    );
  }
}
